import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    // 登录/注册等无需侧栏布局
    { path: '/login', name: 'login', component: () => import('@/views/auth/Login.vue') },
    { path: '/register', name: 'register', component: () => import('@/views/auth/Register.vue') },
    { path: '/forgot', name: 'forgot', component: () => import('@/views/auth/ForgotPassword.vue') },
    {
      path: '/',
      component: () => import('@/layouts/MerchantLayout.vue'),
      children: [
        { path: '', redirect: '/dashboard' },
        { path: 'dashboard', name: 'dashboard', component: () => import('@/views/Dashboard.vue') },
        { path: 'product/list', name: 'product-list', component: () => import('@/views/product/List.vue') },
        { path: 'order/list', name: 'order-list', component: () => import('@/views/order/List.vue') },
        { path: 'finance/overview', name: 'finance-overview', component: () => import('@/views/finance/Overview.vue') },
        { path: 'settings/profile', name: 'settings-profile', component: () => import('@/views/settings/Profile.vue') },
        { path: 'product/edit', name: 'product-edit', component: () => import('@/views/product/Edit.vue') },
        { path: 'order/detail', name: 'order-detail', component: () => import('@/views/order/Detail.vue') },
      ]
    },
  ],
})

// 登录守卫：未登录访问受保护路由时，跳转到 /login
router.beforeEach((to, from, next) => {
  const PUBLIC = ['/login', '/register', '/forgot']
  if (PUBLIC.includes(to.path)) return next()
  try{
    const token = localStorage.getItem('merchant_accessToken') || localStorage.getItem('accessToken')
    if (!token) return next({ path: '/login', query: { redirect: to.fullPath } })
  }catch(e){}
  next()
})

export default router
